#!/bin/bash

# 餐厅发现应用 Docker 部署脚本
# 使用方法: ./deploy.sh [dev|prod] [--with-redis]

set -e

# 默认参数
ENVIRONMENT="prod"
WITH_REDIS=false
IMAGE_NAME="restaurantfinder"
IMAGE_TAG="latest"

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        dev|development)
            ENVIRONMENT="dev"
            shift
            ;;
        prod|production)
            ENVIRONMENT="prod"
            shift
            ;;
        --with-redis)
            WITH_REDIS=true
            shift
            ;;
        -t|--tag)
            IMAGE_TAG="$2"
            shift 2
            ;;
        -h|--help)
            echo "使用方法: $0 [dev|prod] [--with-redis] [-t|--tag <标签>]"
            echo ""
            echo "选项:"
            echo "  dev|prod      部署环境 (默认: prod)"
            echo "  --with-redis  启用Redis缓存服务"
            echo "  -t|--tag      指定镜像标签 (默认: latest)"
            echo "  -h|--help     显示此帮助信息"
            exit 0
            ;;
        *)
            echo "未知参数: $1"
            exit 1
            ;;
    esac
done

echo "🚀 开始部署餐厅发现应用..."
echo "📋 部署配置:"
echo "   - 环境: $ENVIRONMENT"
echo "   - Redis: $WITH_REDIS"
echo "   - 镜像标签: $IMAGE_TAG"
echo ""

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "❌ 错误: Docker未安装，请先安装Docker"
    exit 1
fi

# 检查docker-compose是否安装
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo "❌ 错误: docker-compose未安装，请先安装docker-compose"
    exit 1
fi

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down --remove-orphans || true

# 构建镜像
echo "🔨 构建Docker镜像..."
docker build -t $IMAGE_NAME:$IMAGE_TAG .

# 准备环境变量
ENV_FILE="docker.env"
if [ ! -f "$ENV_FILE" ]; then
    echo "⚠️  警告: $ENV_FILE 文件不存在，将使用默认配置"
    echo "请复制并配置 docker.env 文件中的环境变量"
fi

# 构建docker-compose命令
COMPOSE_CMD="docker-compose"
if docker compose version &> /dev/null; then
    COMPOSE_CMD="docker compose"
fi

# 启动服务
echo "🏃 启动服务..."
if [ "$WITH_REDIS" = true ]; then
    echo "📦 启用Redis缓存服务..."
    $COMPOSE_CMD --profile cache up -d
else
    $COMPOSE_CMD up -d restaurantfinder
fi

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 10

# 检查服务状态
echo "🔍 检查服务状态..."
if curl -f http://localhost:8080/health > /dev/null 2>&1; then
    echo "✅ 服务启动成功!"
    echo "🌐 应用访问地址: http://localhost:8080"
    echo ""
    echo "📊 容器状态:"
    $COMPOSE_CMD ps
    echo ""
    echo "📝 查看日志: $COMPOSE_CMD logs -f"
    echo "🛑 停止服务: $COMPOSE_CMD down"
else
    echo "❌ 服务启动失败，请检查日志:"
    $COMPOSE_CMD logs restaurantfinder
    exit 1
fi 